<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/4
 * Time: 14:51
 */

namespace common\business\empdept;


use common\business\DbHandler;
use common\models\Department;
use common\models\Employee;
use common\models\EmployeeDepartment;
use common\result\ActionResult;

class EmployeeDepartmentApiHandler extends DbHandler
{
    /**
     * @param $obj EmployeeDepartment
     * @return ActionResult
     */
    public function createEmployeeDepartment($obj){
        $this->updateDepartmentAndEmployee($obj);
        return $this->create($obj);
    }

    /**
     * @param $obj EmployeeDepartment
     */
    protected function updateDepartmentAndEmployee($obj){
        $deptInDb = Department::findOne([
            'number' => $obj->department_number
        ]);
        if ($deptInDb){
            $obj->department_id = $deptInDb->id;
        }
        $employeeInDb = Employee::findOne([
            'number' => $obj->employee_number
        ]);
        if($employeeInDb){
            $obj->employee_id = $employeeInDb->id;
        }
    }

    /**
     * @param EmployeeDepartment $newObj
     * @param EmployeeDepartment $oldObj
     * @return ActionResult
     */
    public function updateEmployeeDepartment($newObj, $oldObj = null){
        $this->updateDepartmentAndEmployee($newObj);
        if (!$oldObj){
            $oldObj = EmployeeDepartment::findOne([
                'id' => $newObj->id,
            ]);
        }
        return $this->update($newObj, $oldObj, [
            'employee_id',
            'employee_number',
            'employee_name',
            'department_id',
            'department_number',
            'department_name',
            'department_display_name',
            'hr_status',
            'qywx_status',
            'level',
        ]);
    }
}